<template>
	<!-- :style="{background: isSearch ? '#f7f7f7' : '#fafafa'}" -->
	<view class="app-layout" style="background-color: #F7F7F7;">
		<app-layout>
			<view class="search">
				<view class="top">
					<view class="dir-left-nowrap box">
						<input type="text" class="box-grow-1 input" confirm-type="搜索" @input="input" @confirm="search"
							v-model="keyword" placeholder="搜索">
						<view class="close-tip" @click="clear">
							<image class="search-close" v-if="keyword" src="/static/image/icon/delete-yuan.png"></image>
						</view>
						<view class="box-grow-0 cross-center" @click="search">搜索</view>
					</view>
				</view>
				<!-- hidden -->
				<view style="height: 104rpx"></view>

				<!-- 2021.9.27 9.28 保持一直固定在搜索框下 -->
				<view class="" v-show="!isSearch">
					<!-- 历史搜索 -->
					<view class="history">
						<view class="dir-left-nowrap cross-center title">
							<view class="box-grow-1">历史搜索</view>
							<image src="/static/image/icon/delete.png" class="box-grow-0" @click="deleteHistory">
							</image>
						</view>
						<view class="dir-left-wrap list" v-if="historyList.length > 0">
							<view class="dir-left-wrap box-grow-1">
								<block v-for="(item, index) in historyList" :key="index">
									<view class="box-grow-0 cross-center item once-item"
										@click="historyClick(item.keyword)">
										<view class="t-omit" style="max-width: 650rpx">{{item.keyword}}</view>
									</view>
								</block>
							</view>
						</view>
					</view>
					<!-- 首页80频道 -->
					<view class="hot-center">
						<view class="top-list">
							<view v-for="(goods,index) in navs" :key="index" class="item cross-center dir-left-nowrap"
								@click="goodsNav(goods.url)">
								<view class="box-grow-0 main-center first">
									<view>{{goods.sort}}</view>
								</view>
								<view class="goods-image box-grow-0">
									<image :src="goods.icon_url"></image>
								</view>
								<view class="goods-name t-omit">{{goods.name}}</view>
							</view>
						</view>
					</view>
				</view>
				<view v-if="isSearch" class="goods-list">
					<template v-if="list.length <= 0">
						<view class="main-center no-result">
							<view class="dir-left-nowrap cross-center">
								<image class="box-grow-0 empty" src="../../static/image/icon/empty.png"></image>
								<view class="box-grow-1">
									<view>抱歉，没有相关商品</view>
									<view v-if="!mch_id" class="text">以下是为您推荐的商品</view>
								</view>
							</view>
						</view>
					</template>
					<view style="background-color: #f7f7f7">
						<u-ordinary-list :reset="goodsReset" :pagination="true" :isShowAttr="true" :list="newList"
							:theme="getTheme" :list-style="2"></u-ordinary-list>
					</view>
				</view>
				<view class="u-loading-list" v-if="loading">加载中...</view>
			</view>
		</app-layout>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex';
	import uOrdinaryList from '../../components/page-component/u-goods-list/u-ordinary-list.vue';
	let page = 1;
	let is_loading = false;
	let is_no_more = false;
	let beginAfter = true;
	let mallurl = null

	export default {
		name: "search",
		components: {
			uOrdinaryList
		},
		data() {
			return {
				list: [],
				isSearch: false,
				historyList: [],
				keyword: '',
				limit: 10,
				pagecount: 1,
				pid: 0,
				// beginAfter: true,
				tempList: [],
				realHistoryList: [],
				loading: false,
				// 9.28 调换主题和视频
				searlist: [{
						id: 2,
						title: '商品'
					},
					{
						id: 1,
						title: '主播'
					},
				],
				// 9.28 默认主题
				se_id: 2,
				// 分类列表
				catelist: [],

				iscatelist: 2,

				navs: [],
				recommend_list: [],
				goodsReset: false
			};
		},
		computed: {
			...mapGetters('mallConfig', {
				getTheme: 'getTheme',
				getSetting: 'getSetting',
			}),
			newList() {
				if (this.list.length > 0) {
					return this.list;
				} else {
					return this.recommend_list;
				}
			},
			sizeTransform() {
				const windowWidth = uni.getSystemInfoSync().windowWidth;
				const p = 750 / windowWidth;
				const boxLeft = 24 / p;
				const marginRight = 20 / p;
				const btnWidth = 60 / p;
				const listWidth = windowWidth - boxLeft * 2;
				return {
					p,
					boxLeft,
					marginRight,
					btnWidth,
					listWidth
				}
			},
		},
		onLoad(options) {
			mallurl = this.$siteInfo.apiroot + '?_mall_id=2&r='
			if (options.cid) {
				this.pid = parseInt(options.cid)
				this.keyword = options.keyword
			}
			if (options.iscate) {
				this.iscatelist = parseInt(options.iscate)
				if (this.iscatelist == 1) {
					// 9.28 跳转到视频时 重置与正常不同 加se_id视频列表得标记
					this.resetglist();
					return
				}
			}
			this.se_id = 2
			page = 1;
			is_loading = false;
			is_no_more = false;
			this.historyList = this.getHistory();
			this.getSelect();
			// 9.28 默认情况下 显示所有主题
			this.allReq(2)
			// this.getCateList()
		},
		onReady() {
			if (this.keyword != '') {
				uni.setNavigationBarTitle({
					title: this.keyword
				})
			}
		},
		onReachBottom() {
			if (is_no_more) {

			} else {
				this.goodsReset = false;
				if (this.keyword) {
					this.loading = true;
					this.getGoodsList();
				}
			}
		},
		watch: {
			keyword: {
				handler(v) {
					if (v == '') {
						this.cancel();
					}
				},
				immediate: true,
			}
		},
		methods: {
			allReq(pid) {
				this.$request({
					url: this.$api.navs.list,
					data: {
						pid: pid,
						status: 1,
						limit: 200
					}
				}).then((res) => {
					if (res.code == 0) {
						if (pid == 2) {
							this.navs = res.data.list
						}
					}
				}).catch(() => {

				})
			},
			goodsNav(url) {
				uni.navigateTo({
					url: url
				});
			},
			change(id) {
				this.se_id = id
				if (id == 2) {
					page = 1
				} else if (id == 1) {
					page = 1
				}
			},
			toList(item) {
				uni.navigateTo({
					url: '/pages/sixty/search/search?cid=' + item.id + '&iscate=1&keyword=' + item.title
				})
			},
			// 历史记录显示 width/height
			async getSelect() {
				const historyList = this.historyList;
				if (historyList && historyList.length) {
					const self = this;
					setTimeout(() => {
						// #ifndef MP-WEIXIN
						let query = uni.createSelectorQuery();
						// #endif
						// #ifdef MP-WEIXIN
						let query = uni.createSelectorQuery().in(this);
						// #endif
						query.selectAll('.once-item').fields({
							size: true,
						}, function(res) {
							// console.log(res,'getselect');
							self.formatData(res);
							if (beginAfter) {
								// console.log(self.beginAfter,'self.beginAfter');
								self.selectLimitList(res);
							} else {
								self.selectAllList();
							}
						}).exec();
					}, 500)
				}
			},
			formatData(res) {
				// console.log(res,'formatData');
				const self = this;
				const historyList = self.historyList;
				const {
					marginRight,
					listWidth
				} = self.sizeTransform;

				//列表格式化
				let tempList = [];
				let item = [];
				let line_width = 0;
				for (let i = 0; i < res.length; i++) {
					const alone_width = res[i].width + marginRight;
					let alone_width_count = alone_width + line_width;
					if (alone_width_count <= listWidth) {
						item.push(historyList[i]);
						line_width = alone_width_count;
					} else {
						if (item.length === 0 && line_width === 0) {
							tempList.push([historyList[i]]);
						} else {
							tempList.push(item);
							line_width = 0;
							item = [];
							i--;
						}
					}
				}
				if (item.length) {
					tempList.push(item);
				}
				this.tempList = tempList;
			},
			selectLimitList(res) {
				const self = this;
				const {
					btnWidth,
					listWidth,
					marginRight
				} = self.sizeTransform;
				let newArr = JSON.parse(JSON.stringify(self.tempList));
				let realHistoryList = [];
				if (newArr.length > 2) {
					let indexMore = 0;
					const secondWidth = listWidth - btnWidth - marginRight;
					let maxWidth = 0;
					newArr[1].forEach((item, index) => {
						maxWidth += res[newArr[0].length + index].width + marginRight
						if (maxWidth <= secondWidth) {
							indexMore = index + 1;
						}
					})
					newArr[1].splice(indexMore, newArr[1].length - indexMore, {
						mark: true,
					});
					realHistoryList = [newArr[0], newArr[1]];
					beginAfter = true;
				} else {
					newArr.forEach(item => realHistoryList.push(item));
					beginAfter = false;
				}
				self.realHistoryList = realHistoryList;
			},
			selectAllList() {
				const tempList = this.tempList;
				let arr = [];
				if (tempList && tempList.length) {
					for (let i = 0; i < 5 && i < tempList.length; i++) {
						arr.push(tempList[i]);
					}
				}
				beginAfter = false;
				this.realHistoryList = arr;
			},
			// 9.28 删除为空时
			input(e) {
				if (e.detail.value == '') {
					this.reset();
				}
			},
			search() {
				let keyword = this.keyword;
				this.keyword = keyword.trim();
				this.$showLoading();
				if (this.keyword === '') {
					uni.showToast({
						title: '请输入您想搜索的内容',
						icon: 'none'
					})
					return;
				}
				// 历史记录
				this.setHistory();
				// 历史记录
				this.getSelect();
				// 搜索结果
				this.reset();
			},
			reset() {
				// page = 1;
				// this.se_id = 2
				// is_no_more = false;
				// this.isSearch = true
				// this.list = []
				// this.catelist = []
				page = 1;
				is_no_more = false;
				this.goodsReset = true;
				this.getGoodsList();
			},
			getGoodsList() {
				if (!this.keyword) return;
				if (is_loading) return;
				is_loading = true;
				let url = mallurl + this.$apiUrl.default.goods_list
				this.$request({
					url: url,
					data: {
						keyword: this.keyword,
						page: page,
					}
				}).then(response => {
					is_loading = false;
					this.$hideLoading();
					this.isSearch = true;
					this.loading = false;
					let {
						code,
						data,
						msg
					} = response;
					if (code === 0) {
						if (page === 1) this.list = [];
						if (data.list.length > 0) {
							this.list.push(...data.list);
							page++;
						} else {
							is_no_more = true;
							if (page === 1) this.getRecommend();
						}
					} else {
						uni.showModal({
							content: msg
						})
					}
				}).catch(() => {
					this.$hideLoading();
					is_loading = false;
				});
			},
			getRecommend() {
				if (this.recommend_list.length > 0) return;
				let url = mallurl + this.$apiUrl.goods.new_recommend
				this.$request({
					url: url,
					data: {
						goods_id: 0,
						type: 'goods'
					}
				}).then(response => {
					this.$hideLoading();
					if (response.code === 0) this.recommend_list = response.data.list;
				}).catch(()=>{
					this.$hideLoading();
				});
			},
			resetglist() {
				page = 1;
				this.se_id = 1
				is_no_more = false;
				this.isSearch = true
				this.list = []
				this.catelist = []
			},

			clear() {
				uni.hideKeyboard()
				this.keyword = '';
				this.loading = false;

				// 9.28 清空时搜索默认主题
				this.reset()
			},

			cancel() {
				this.isSearch = false;
				this.loading = false;
				this.keyword = '';
				this.list = [];
			},

			// 历史记录
			setHistory() {
				let historyList = this.getHistory();
				let keyword = this.keyword.trim();

				historyList.forEach((item, index) => {
					if (item.keyword === keyword) historyList.splice(index, 1);
				});
				historyList.unshift({
					keyword: keyword,
				});
				if (historyList.length > 20) historyList.pop();
				this.historyList = historyList;
				uni.setStorageSync("HISTORY_LIST", historyList);
			},
			getHistory() {
				let historyList = uni.getStorageSync('HISTORY_LIST');
				if (!historyList) historyList = [];
				return historyList;
			},
			deleteHistory() {
				let self = this;
				uni.showModal({
					content: '确认删除全部历史记录？',
					success: function(res) {
						if (res.confirm) {
							uni.removeStorageSync("HISTORY_LIST");
							self.historyList = [];
						}
					}
				});
			},
			historyClick(keyword) {
				this.keyword = keyword.trim();
				this.$showLoading();
				this.reset();
			},
		}
	}
</script>

<style scoped lang="scss">
	.threefix {
		// position: fixed;
		// top: 0;
		position: sticky;
		top: 104rpx;
		width: 100%;
		background-color: #FFFFFF;
		left: 0;
		z-index: 999;
	}

	.flex {
		// position: fixed;
		// top: 102rpx;
		// left: 0;
		width: 100%;
		display: flex;
		justify-content: space-around;
		align-items: center;
		padding: 24rpx 0;
		height: 120rpx;
		background-color: #FFFFFF;
		z-index: 666;

		.item {
			width: 200rpx;
			height: 72rpx;
			line-height: 72rpx;
			position: relative;
			text-align: center;
			font-size: 28rpx;

			&.active:before {
				position: absolute;
				bottom: 0;
				left: 0;
				content: '';
				font-weight: 500;
				background: #342B2A;
				border-radius: 4rpx;
				width: 200rpx;
				left: 50%;
				transform: translateX(-50%);
				height: 8rpx;
			}
		}
	}

	.opacity-hide {
		position: fixed;
		top: 0;
		z-index: -10;
		opacity: 0;
		overflow: hidden;
	}

	.search {
		background-color: #efeff4;
	}

	.close-pic {
		margin-right: #{20rpx};
		margin-bottom: #{16rpx};
		border-radius: 50%;

		image {
			height: #{60rpx};
			width: #{60rpx};
			display: block;
		}
	}

	.hot-center {
		background-color: #fafafa;
		padding: #{32rpx} #{24rpx};

		.top-image {
			width: #{159rpx};
			height: #{25rpx};
			display: block;
		}

		.top-list {
			border-radius: #{16rpx};
			padding: #{32rpx - 10rpx} 0;
			box-shadow: 0 0 #{12rpx} 0 #e0e0e0;

			.item {
				height: #{110rpx};

				.first {
					width: #{120rpx};
					font-weight: bold;

					image {
						width: #{48rpx};
						height: #{43rpx};
						display: block;
					}

					view {
						color: #999999;
						font-size: #{26rpx};
					}
				}

				.goods-image {
					image {
						height: #{90rpx};
						width: #{90rpx};
						display: block;
						border-radius: #{8rpx};
					}
				}

				.goods-name {
					color: #333333;
					font-size: #{26rpx};
					margin: 0 #{24rpx};
				}
			}
		}
	}

	.app-layout {
		min-height: 100vh;
	}

	.top {
		position: fixed;
		width: 100%;
		top: 0;
		z-index: 15;
		padding: #{20rpx} #{24rpx};
		background-color: #efeff4;
		font-size: $uni-font-size-import-two;
		color: $uni-general-color-one;

		.input {
			background-color: #ffffff;
			border-radius: #{50rpx 0 0 50rpx};
			padding: 0 #{32rpx};
			font-size: $uni-font-size-general-one;
			height: #{64rpx};
		}

		.box {
			position: relative;
			font-size: 28rpx;

			.close-tip {
				width: #{64rpx};
				height: #{64rpx};
				background-color: #ffffff;
				border-radius: #{0 50rpx 50rpx 0};
				margin-right: #{20rpx};
			}

			.search-close {
				width: #{32rpx};
				height: #{32rpx};
				border-radius: 50%;
				margin: #{16rpx};
			}
		}

		.radio {
			margin-top: #{32rpx};

			.radio-item {
				padding-bottom: #{12rpx};
			}

			.active {
				border-bottom: #{4rpx} solid;
			}
		}
	}

	.history {
		padding: #{36rpx} #{24rpx};
		border-radius: 16rpx 16rpx 0 0;
		background-color: #ffffff;
		font-size: $uni-font-size-general-one;
		// border-bottom: 1rpx solid #e0e0e0;

		.title {
			padding-bottom: #{24rpx};
			color: $uni-general-color-one;

			image {
				width: #{28rpx};
				height: #{34rpx};
				display: block;
			}
		}

		.list {
			.item {
				height: #{64rpx};
				// background-color: #f7f7f7;
				padding: 0 #{20rpx};
				margin-right: #{20rpx};
				margin-bottom: #{16rpx};
				border-radius: #{32rpx};
			}
		}
	}

	.goods-list {
		background-color: #f7f7f7;

		.no-result {
			height: #{156rpx};
			padding: #{28rpx} 0;
			font-size: $uni-font-size-general-one;
			background-color: #ffffff;

			.text {
				color: $uni-general-color-two;
			}

			.empty {
				width: #{100rpx};
				height: #{100rpx};
				display: block;
				margin-right: #{40rpx};
			}
		}
	}

	.record {
		width: 100%;
		background-color: #FFFFFF;
		height: 20rpx;
		line-height: 20rpx;
		font-size: $uni-font-size-general-one;
		color: $uni-general-color-two;
		text-align: center;
	}

	.no-result {
		height: #{156rpx};
		padding: #{28rpx} 0;
		font-size: $uni-font-size-general-one;
		background-color: #ffffff;

		.text {
			color: $uni-general-color-two;
		}

		.empty {
			width: #{100rpx};
			height: #{100rpx};
			display: block;
			margin-right: #{40rpx};
		}
	}

	.u-loading-list {
		height: 64upx;
		line-height: 64upx;
		text-align: center;
		color: #b0b0b0;
		font-size: 24upx;
		// background-color: #f7f7f7;
	}

	.beturnstore {
		background: #FFFFFF;
		width: 686rpx;
		height: 128rpx;
		border-radius: 16rpx;
		margin: 20rpx auto;
		color: #333333;
		display: flex;
		align-items: center;
		padding: 0 48rpx;
		box-shadow: 0px 5rpx 10rpx rgba(57, 57, 57, 0.1);
	}

	.beturnimage {
		width: 84rpx;
		height: 84rpx;
		border-radius: 50%;
	}

	.beturnimage .image {
		width: 84rpx;
		height: 84rpx;
		border-radius: 50%;
	}

	.beturntext {
		font-size: 28rpx;
		color: #333333;
		padding-left: 32rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
</style>
